package shuai.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import shuai.model.Userme;
import shuai.service.UserService;
import javax.servlet.http.HttpSession;
import java.util.logging.Logger;


@Controller
public class UserController {

    private static Logger logger = Logger.getLogger(UserController.class.toString());
    @Autowired
    private UserService userService;
    @RequestMapping("/gotoLogin")
    public String gotoLogin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(@RequestParam(value = "loginName",required = true)String loginNmae, String password, Model molde,
                        HttpSession httpSession) {
        logger.info("登录用户名" + loginNmae);
        //用redirect和forward标签返回
        //注意:用这两个标签必须写全路径,不适应视图解析的逻辑视图
        if (StringUtils.isNotEmpty(loginNmae) && StringUtils.isNotEmpty(password)) {
            Userme userme = userService.loginUser(loginNmae, password);
            if (userme != null) {
                logger.info("登陆成功");
                httpSession.setAttribute("user", userme);
                return "redirect:/main";
            } else {
                molde.addAttribute("loginFlag", "登陆失败，请输入争取的用户名和密码");
                return "forward:/WEB-INF/pages/login.jsp";
            }
        }else{
            molde.addAttribute("loginFlag","登陆失败,请输入正确的用户名和密码");
            return "forward:/WEB-INF/pages/login.jsp";
        }

    }
    @RequestMapping("/gotoRegister")
    public String gotoRegister(){
        return "register";
    }
    @RequestMapping("/register")
    public String register(Userme userme, Model molde) throws Exception {
        logger.info("登录用户名" + userme);
        if (StringUtils.isNotEmpty(userme.getUsername())&&StringUtils.isNotEmpty(userme.getPassword())){
            boolean b=userService.regiterUser(userme);
            if (b){
                return "forward:/WEB-INF/pages/login.jsp";
            }else{
                molde.addAttribute("loginFlag", "已存在相同用户名");
                return "forward:/WEB-INF/pages/register.jsp";
            }
        }else{
            molde.addAttribute("loginFlag", "请输入用户名密码");
            return "forward:/WEB-INF/pages/register.jsp";
        }

    }

    @RequestMapping("/main")
    public String main(){
        return "main/main";
    }
}
